package com.hhq.core;

import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; 

/**
 * @author 霍华骑
 * 实例化一个对象，然后设置HOST和PORT，
 * 最后调用startServer方法启动
 */
public class Server {
    
    public static String HOST = Config.HOST;
    public static int PORT = Config.PORT;
    public static int num = Config.num;   // 同时连接数量

    public static boolean running = true;

    public static void startServer() throws Exception{
        // 线程池
        ExecutorService pools = Executors.newFixedThreadPool(num); 

        InetAddress inetAddress = InetAddress.getByName(HOST);
        ServerSocket serverSocket = new ServerSocket(PORT, num, inetAddress);
        System.out.println("开始监听：" + inetAddress.getHostAddress()+ ":"+ PORT);
        try{
            while(running){
                Socket socket = serverSocket.accept();
                DealThread dealThread = new DealThread(socket);
                dealThread.setDaemon(true);
                pools.submit(dealThread); // 添加到线程池
                
                // dealThread.start();
            }
        }catch(Exception e){
            serverSocket.close();
        }finally{
            serverSocket.close();
            pools.shutdown();
        }
    }

}